//
//  ServiceImagesListViewController.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/4/24.
//

import UIKit
import HandyJSON
import Photos
import PhotosUI
import MBProgressHUD
import SnapKit
import CoreServices
import PDFKit

class ServiceImagesListViewController: BaseViewController {
    var model: ServiceDetailModel!
    let customView = ServiceImagesListView()
    var bottomOperateList = [CellModel]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.model = ServiceDetailModelHelper.shared.serviceDetailModel
        if let data = self.model.checklists.first(where: {$0.id == ServiceDetailModelHelper.shared.checklistModel.id}){
            ServiceDetailModelHelper.shared.checklistModel = data
        }
        self.initUI()
        //预览图片或pdfe
        self.customView.previewClosure = {[weak self] (row) in
            guard let strongSelf = self else {return}
            
            let iModel: CheckListImageDBModel = ServiceDetailModelHelper.shared.checklistModel.images[row]
            let imagePath = iModel.image
            if imagePath.contains(APPConfig.PDFSuffix){
                let vc = AttachmentViewController()
                vc.attchmentType = .ChecklistPDF
                vc.attachmentURL = imagePath
                vc.attachmentTitle = ""
                strongSelf.navigationController?.pushViewController(vc, animated: false)
            }else{
                let (imagesList, index) = strongSelf.getAllImagePathAndIndex(iModel)
                if imagesList.count > 0 {
                    let vc = BrowseImageViewController()
                    vc.imagesArray = imagesList
                    vc.currentIndex = index
                    strongSelf.navigationController?.pushViewController(vc,animated: true)
                }
            }
        }
        //删除图片或pdf
        self.customView.deleteClosure = {[weak self] (row) in
            guard let strongSelf = self else {return}
            //处理上传完后需重新设置数据
            guard let data = strongSelf.model.checklists.first(where: {$0.id == ServiceDetailModelHelper.shared.checklistModel.id}) else {return}
            ServiceDetailModelHelper.shared.checklistModel = data
            guard row < ServiceDetailModelHelper.shared.checklistModel.images.count else {return}
            let imageModel = ServiceDetailModelHelper.shared.checklistModel.images[row]
            let imagePath = imageModel.image
            let pdfFlag = imagePath.contains(APPConfig.PDFSuffix)
            //image没在上传中，才可以做删除；如果在上传过程中，则不能进行删除（会导致数据错乱）
            if DBManager.shared.checkIfImageUploadingByRecordAt(imageModel,jobType: .serviceJob) {
                Tool().showAlertViewWithOneBtn(message: "The current \(pdfFlag ? "file" : "image") is being uploaded and cann't be deleted.")
            }else{
                
                Tool().showAlertViewWithTwoBtns(title:  "Delete \(pdfFlag ? "File" : "Image")", message: "Are you sure to delete this \(pdfFlag ? "file" : "image")?",yesClosure: {
                    ServiceDetailModelHelper.shared.checklistModel.localDeletedImages.append(imageModel)
                    if imagePath.contains("http"){//server
                        imageModel.pvd_id = strongSelf.model.serviceID
                        imageModel.checklist_id = ServiceDetailModelHelper.shared.checklistModel.id
                        imageModel.title = ServiceDetailModelHelper.shared.checklistModel.title
                        imageModel.oper_type = DataOperType.Del.rawValue
                        DBManager.shared.insertServiceChecklistImages(model: imageModel)
                        //有网络才能请求删除删除
                        if Connectivity.isConnectedToInternet {
                            ModelViewUtil.shared.showLoadingView("Deleting...")
                            UploadManager.shared.uploadServiceChecklistImage(imageModel: imageModel) { successFlag in
                                ModelViewUtil.shared.hideLoadingView()
                            }
                        }
                    }else{//delete 本地数据
                        DBManager.shared.deleteServiceChecklistImageData(model: imageModel)
                    }
                    //删除当前checklist image中的数据，并触发所有刷新
                    ServiceDetailModelHelper.shared.checklistModel.images.remove(at: row)
                    if let index = strongSelf.model.checklists.firstIndex(where: {$0.id == ServiceDetailModelHelper.shared.checklistModel.id}){
                        ServiceDetailModelHelper.shared.serviceDetailModel.checklists[index] = ServiceDetailModelHelper.shared.checklistModel
                        ServiceDetailModelHelper.shared.serviceDetailModel.broadCastChecklistData()
                    }
                })
            }
        }
        
    }
    private func initUI(){
        //top view
        self.view = self.customView
        self.customView.setTitleInfo(ServiceDetailModelHelper.shared.checklistModel.title)
        
        //1.set top data
        self.customView.setData()
        self.bottomOperateList = self.getOperationList()
        self.customView.initBottomView(self.bottomOperateList)
        //拍照
        self.customView.takePhotoClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.takePhoto()
        }
        //选择图库
        self.customView.choosePictureClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.selectFromPhotosLibrary()
        }
        //多选按钮Add attach们额头
        self.customView.addAttachmentClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.addAttachment()
        }
    }
    
    //MARK: 获取底部操作有几个菜单，少于三个直接显示在底部，大于等于三个只显示Add Attachment
    private func getOperationList()->[CellModel]{
        var cellList = [CellModel]()
        cellList.append(CellModel(title: CheckListImageFromType.takePhoto.rawValue))
        cellList.append(CellModel(title: CheckListImageFromType.chooseFromLibrary.rawValue))
        cellList.append(CellModel(title: CheckListImageFromType.uploadPdf.rawValue))
        return cellList
    }
    //MARK: 多选按钮Add attachment
    fileprivate func addAttachment(){
        let actionSheetView = CustomActionSheet(title: R.string.localizable.addDocument(), aCellArray: self.bottomOperateList, aCancelModel: CellModel(title: R.string.localizable.cancel()), aSelectedClosure: { [weak self](row) in
            guard let strongSelf = self else {return}
            switch strongSelf.bottomOperateList[row].title {
            case CheckListImageFromType.takePhoto.rawValue:
                strongSelf.takePhoto()
            case CheckListImageFromType.chooseFromLibrary.rawValue:
                strongSelf.selectFromPhotosLibrary()
            case CheckListImageFromType.uploadPdf.rawValue:
                if #available(iOS 14.0, *) {
                    let vc = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.pdf])
                    vc.allowsMultipleSelection = false//不允许多选
                    vc.delegate = strongSelf
                    vc.modalPresentationStyle = .overFullScreen
                    strongSelf.navigationController?.present(vc, animated: true, completion: nil)
                } else {
                    let vc = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as String], in: UIDocumentPickerMode.import)
                    vc.allowsMultipleSelection = false//不允许多选
                    vc.delegate = strongSelf
                    vc.modalPresentationStyle = .overFullScreen
                    strongSelf.navigationController?.present(vc, animated: true, completion: nil)
                }
            default:
                break
            }
        }, aCancelClosure: nil)
        self.navigationController?.view.addSubview(actionSheetView)
    }
    private func takePhoto(){
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
            DispatchQueue.main.async {
                if status {
                    let vc = TakePhotoViewController()
                    vc.photosCnt = ServiceDetailModelHelper.shared.checklistModel.images.count
                    vc.naviTitle = ServiceDetailModelHelper.shared.checklistModel.title
                    vc.takePhotoClosure = {image in
                        //处理并保存图片
                        let imageData = MediaUtil().resetSizeOfImageData(source_image: image)
                        PhotosManager.shared.saveServiceImageData(imageData as Data, fileType: .image )
                    }
                    //在Take photo 中点击相册
                    vc.selectPhotosFromLibraryClosure = { assert in
                        if ServiceDetailModelHelper.shared.checklistModel.images.count <= 0 {
                            ServiceDetailModelHelper.shared.checklistModel.answered_at = DateUtil().getCurrentDatetime()
                        }
                        PhotosManager.shared.addImageFromPhotosForServiceJob(assert)
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    Tool().showAlertViewWithOneBtn(message: NSLocalizedString("camera.permission", comment: ""))
                }
            }
        }
    }
    //MARK: - 选择相册
    private func selectFromPhotosLibrary(){
        PhotosManager.shared.initData(vc: self, maxCount: 10, closure: { pHAssert, errmsg in
            if let _ = errmsg{
                Tool().showAlertViewWithOneBtn(message: errmsg!)
            }else if let data = pHAssert as? PHAsset{
                if ServiceDetailModelHelper.shared.checklistModel.images.count <= 0 {
                    ServiceDetailModelHelper.shared.checklistModel.answered_at = DateUtil().getCurrentDatetime()
                }
                PhotosManager.shared.addImageFromPhotosForServiceJob(data)
            }
        }).getPhotos(assertFLag: true)
    }

    //MARK: - take photo和selectImageFromlibray共用此代码
    fileprivate func saveImageData(_ resultData: NSData?, fileType: ChecklistFileType = .image){
        guard let originImageData = resultData else{return}
        let fileName = DateUtil().getCurrentDatetimeTamp()
        //checklist image
        
        var imagePath = ""
        if fileType == .image {
            imagePath = FileUtil().getServiceChecklistImagePath(fileName,fileSuffix: APPConfig.ImageSuffix)
            
        }else{
            imagePath = FileUtil().getServiceChecklistImagePath(fileName,fileSuffix: APPConfig.PDFSuffix)
        }
        do {
            try originImageData.write(to: URL(fileURLWithPath: imagePath), options: [.atomic])
            
            let imageModel = CheckListImageDBModel()
            imageModel.pvd_id = self.model.serviceID
            imageModel.checklist_id = ServiceDetailModelHelper.shared.checklistModel.id
            imageModel.record_at = DateUtil().getCurrentDatetime()
            imageModel.image = imagePath
            imageModel.id = fileName
            imageModel.title = ServiceDetailModelHelper.shared.checklistModel.title
            imageModel.oper_type = DataOperType.Add.rawValue
            
            //0.必须先插入数据库，因为broadCast时，有地方（flush upload）会用到本地数据的统计
            DBManager.shared.insertServiceChecklistImages(model: imageModel)
            //1.增加到当前list中
            ServiceDetailModelHelper.shared.checklistModel.images.insert(imageModel, at: 0)
            if let index = self.model.checklists.firstIndex(where: {$0.id == ServiceDetailModelHelper.shared.checklistModel.id}){
                ServiceDetailModelHelper.shared.serviceDetailModel.checklists[index] = ServiceDetailModelHelper.shared.checklistModel
                ServiceDetailModelHelper.shared.serviceDetailModel.broadCastChecklistData()
            }
            //2.上传
            //需要调用上传附件API
            UploadManager.shared.uploadServiceChecklistImage(imageModel: imageModel)
            
        }catch{
            NSLog("Saving checklist image to local failed")
        }
    }
    
    //MARK: - 获取所有的Image类型（过滤掉pdf），及当前选择行的index
    private func getAllImagePathAndIndex(_ selImageModel: CheckListImageDBModel)->([BrowseImageData], Int){
        //1.过滤出来所有的图片，不要pdf
        let resultList: [BrowseImageData] = ServiceDetailModelHelper.shared.checklistModel.images.filter({$0.image.contains(APPConfig.ImageSuffix)}).map { BrowseImageData(image:$0.image)}
        //2.获取当前点击的index
        let index = resultList.firstIndex {  imageModel in
            if imageModel.image == selImageModel.image{
                return true
            }else{
                return false
            }
        }

        return (resultList, index ?? 0)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
}

extension ServiceImagesListViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let firstUrl = urls.first else {return}
        //startAccessingSecurityScopedResource()返回true的话，和stopAccessingSecurityScopedResource成对出现
        let urlAuthrized = firstUrl.startAccessingSecurityScopedResource()
        //获取授权
        //通过文件协调器读取文件地址
        var fileData: Data?
        let fileCoordinator = NSFileCoordinator()
        fileCoordinator.coordinate(readingItemAt: firstUrl, options: [.withoutChanges], error: nil) { (newUrl) in
//            let fileName = newUrl.lastPathComponent
            //读取文件协调器提供的新地址里的数据
            fileData = try? Data.init(contentsOf: newUrl, options: [.mappedIfSafe])
            if let data = fileData {
                PhotosManager.shared.saveServiceImageData(data, fileType: .pdf)
                //获取到数据
//                if let img = self.pdfThumbnail(newUrl), let data = img.jpegData(compressionQuality: 0.5){
//                    self.saveImageData(data as NSData, photoModel: ChecklistPhotoModel())
//                }
            }
        }
        //
        if urlAuthrized {
            firstUrl.stopAccessingSecurityScopedResource()
        }
    }
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        self.dismiss(animated: true)
    }
}
